package com.ghy;

import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterFlowRuleManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 卢佳新
 * @version: v1.0
 * @description: com.ghy.springbootsentinel
 * @date:2022/1/3 15:30
 * @Motto 不积跬步，无以至千里；不积小流，无以成江海。
 */
public class FlowRuleInitFunc implements InitFunc {

    private final String nacosAddress="localhost:8848";
    private final String groupId="SENTINEL_GROUP";//nacos分组
    private final String dataId="-flow-rules";//nacos的data Id配置


    @Override
    public void init() throws Exception {
        registerFlowRule();
    }
    private static void initFlowRule(){
        List<FlowRule> rules=new ArrayList<> ();
        FlowRule flowRule=new FlowRule ();
        flowRule.setResource("doTest"); //针对那个资源设置规则
        flowRule.setGrade( RuleConstant.FLOW_GRADE_QPS);//QPS或者并发数
        flowRule.setCount(5); //QPS=5
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }

    private void registerFlowRule(){
        ClusterFlowRuleManager.setPropertySupplier( namespace->{
            ReadableDataSource<String,List<FlowRule>> flowRuleDs=
                    new NacosDataSource<List<FlowRule>>(nacosAddress,groupId,namespace+dataId,
                            source-> JSON.parseObject(source,new TypeReference<List<FlowRule>>(){}));
            return flowRuleDs.getProperty();
        });
    }
}
